package com.xywy.find;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.shapes.ArcShape;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.xywy.R;
import com.xywy.common.BaseActivity;
import com.xywy.common.constants.ErrorCode;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.util.Constants;
import com.xywy.common.util.FileUtil;
import com.xywy.common.util.MLog;
import com.xywy.common.util.ToastUtil;
import com.xywy.common.widget.CircularImage;
import com.xywy.common.widget.MyProgress;
import com.xywy.common.widget.TitleBar2;
import com.xywy.find.bean.JkzhArticle;
import com.xywy.find.paser.JkgcArticlePaser;
import com.xywy.find.paser.JkzhArticlePaser;
import com.xywy.me.bean.UserKeeper;

/**
 * 健康知乎 - 文章内容页
 * 
 * @author xiaogd
 * 
 */
public class JkzhArticleActivity extends BaseActivity {
	private static final String TAG = "JkzhArticleActivity";
	private String DESCRIPTOR = "com.umeng.share";
	private Context mContext;
	private int target = 5;
	private String back = "";

	private ImageView artImg;
	private TextView title;
	private TextView content;
	private String artid;
	private TextView detail;
	private TextView type;
	private TextView name;
	private CircularImage uPhoto;

//	private TextView good;
//	private TextView share;
//	private TextView collect;

	private Drawable collectDr;
	private Drawable shareDr;
	private Drawable goodD;

	private JkzhArticlePaser paser;
	private int currentState; //当前收藏状态
	
	// 页面状态工具
	private final int DEFAULT = 0; // 当前页面状态是默认的；
	private final int HELPED = 1;// 点击帮助的状态
	private final int COLLECTED = 2;// 点击收藏的状态
	private final int HELPED_AND_COLLECTED = 3;// 帮助和收藏一起的状态

	
	   //点击赞的记录在本地
    private int praiseState;
    private SharedPreferences spState;
	private Editor editor;
	private JkzhArticle article;
	private IWXAPI api;
	
	private ImageView tv_jkgc_article_good;// 赞
	private ImageView tv_jkgc_article_share;// 分享
	private ImageView tv_jkgc_article_collect;// 收藏
	
	public static final int Sta_Click = 2 ;//进入页面
	public static final int Sta_Collect = 0 ;//收藏
	public static final int Sta_Help = 1 ;//进入页面
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置为全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.find_jkzh_article);
		api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
		this.preInit();
		this.initView();
		this.loadData();
	}

	@Override
	public void preInit() {
		mContext = this.context;
		Intent intent = getIntent();
		artid = intent.getStringExtra("artid");
		target = intent.getIntExtra("target", 0);
		paser = new JkzhArticlePaser(mContext, handler);
	}

	@Override
	public void initView() {
		// title
		TitleBar2 titleBar = (TitleBar2) findViewById(R.id.find_jkzh_article_title_bar);
		TextView tvTitle = titleBar.getTitle();
		titleBar.getGo().setVisibility(View.INVISIBLE);
		titleBar.onClickBack(this);

		tvTitle.setText(getString(R.string.find_jkzh_detail));

		artImg = (ImageView) findViewById(R.id.iv_find_jkzh_article_artImg);
		title = (TextView) findViewById(R.id.tv_jkgc_article_title);

		name = (TextView) findViewById(R.id.tv_jkzh_article_name);
		type = (TextView) findViewById(R.id.tv_jkzh_article_type);
		detail = (TextView) findViewById(R.id.tv_jkzh_article_detail);
		content = (TextView) findViewById(R.id.tv_jkzh_article_content);

		uPhoto = (CircularImage) findViewById(R.id.jkzh_cover_user_photo);
//		good = (TextView) findViewById(R.id.tv_jkzh_article_good);
//		share = (TextView) findViewById(R.id.tv_jkzh_article_share);
//		collect = (TextView) findViewById(R.id.tv_jkzh_article_collect);
		
		tv_jkgc_article_good = (ImageView) findViewById(R.id.tv_jkgc_article_good);
		tv_jkgc_article_share = (ImageView) findViewById(R.id.tv_jkgc_article_share);
		tv_jkgc_article_collect = (ImageView) findViewById(R.id.tv_jkgc_article_collect);

		

		// 点击效果
		goodD = mContext.getResources().getDrawable(
				R.drawable.find_article_bar_1_pressed);
		goodD.setBounds(0, 0, goodD.getMinimumWidth(), goodD.getMinimumHeight());

		collectDr = mContext.getResources().getDrawable(
				R.drawable.find_article_bar_3_pressed);
		collectDr.setBounds(0, 0, collectDr.getMinimumWidth(),
				collectDr.getMinimumHeight());

		shareDr = mContext.getResources().getDrawable(
				R.drawable.find_article_bar_2_pressed);
		shareDr.setBounds(0, 0, shareDr.getMinimumWidth(),
				shareDr.getMinimumHeight());
		tv_jkgc_article_collect.setEnabled(false);
//		collect.setEnabled(false);
	}

	@Override
	public void loadData() {
		SharedPreferences sp = context.getSharedPreferences("config",
				Context.MODE_PRIVATE);
//		userid = sp.getString("userid", "");
		userid = UserKeeper.getCurrentUser(this).getUserid();
		this.loadlist();
		getState(Integer.parseInt(artid));
	}

	MyProgress myProgress;

	/**
	 * 返回
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			myProgress.stop();
			if (msg.arg1 == ResultCode.SUCCESS) {
				if (msg.arg2 == JkzhArticlePaser.ARTICLE) {
					shwoView(msg.obj);
					getState();
				}
				if (msg.arg2 == JkzhArticlePaser.GOOD) {
					Toast.makeText(mContext,
							getString(R.string.find_good_success),
							Toast.LENGTH_LONG).show();
				}
				if (msg.arg2 == JkzhArticlePaser.COLLECT) {
					if(currentState ==DEFAULT){
						ToastUtil.showToast(JkzhArticleActivity.this, "收藏成功", Toast.LENGTH_SHORT);
						currentState = COLLECTED;
						Stattistics(Sta_Collect);
					}else {
						ToastUtil.showToast(JkzhArticleActivity.this, "取消收藏", Toast.LENGTH_SHORT);
						currentState = DEFAULT;
					}
			    	setDrawable(currentState);
				}
				else if (msg.arg2 == JkzhArticlePaser.FIND) {
					String jsonStr = (String) msg.obj;
					currentState = DEFAULT;
			    	setDrawable(currentState);
			        try {
			            JSONObject jsonObject = new JSONObject(jsonStr);
			            int state = jsonObject.optInt("state");
			            if(state != 200){
			            	 tv_jkgc_article_collect.setEnabled(true);
			            	 return;
			            }
			            JSONArray jsonArray = jsonObject.getJSONArray("data");
			            if (null != jsonArray && jsonArray.length() > 0) {
			                for (int i = 0; i < jsonArray.length(); i++) {
			                    JSONObject json = jsonArray.getJSONObject(i);
			                    String tempId = json.optString("art_id");
	                            if(artid.equals(tempId)){
	                            	currentState = COLLECTED;
	                            	setDrawable(currentState);
	                            	break;
	                            }
			                     
			                }
			            }
			        }catch (JSONException e){
			            e.printStackTrace();
			            tv_jkgc_article_collect.setEnabled(true);
			        }
			        tv_jkgc_article_collect.setEnabled(true);
				}
			} else if (msg.arg1 == ErrorCode.ERR_NO_NETWORK) {
				Toast.makeText(mContext, getString(R.string.common_net_fail),
						Toast.LENGTH_LONG).show();
				if (msg.arg2 == JkzhArticlePaser.FIND){
					currentState = DEFAULT;
			    	setDrawable(currentState);
			    	tv_jkgc_article_collect.setEnabled(true);
				}
			}else {
				if (msg.arg2 == JkzhArticlePaser.FIND){
					currentState = DEFAULT;
			    	setDrawable(currentState);
			    	tv_jkgc_article_collect.setEnabled(true);
				}else {
//					Toast.makeText(mContext, getString(R.string.common_fail),
//							Toast.LENGTH_LONG).show();
				}
			}

		}
	};
	String titleStr = "";
	String contentStr = "";

	// 页面操作
	private void shwoView(Object object) {
		JkzhArticle articles = (JkzhArticle) object;
		article = (JkzhArticle) object;
		titleStr = articles.getTitle();
		contentStr = articles.getContent();

		title.setText(articles.getTitle());
		name.setText(articles.getNameD());
		type.setText(articles.getType());
		content.setText(Html.fromHtml(articles.getContent()));
		detail.setText(Html.fromHtml(articles.getDetail()));
		// 上方图片
		imageLoader.displayImage(articles.getArtImg(), artImg, options,
				new SimpleImageLoadingListener() {
					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {
						if (loadedImage != null) {
							((ImageView) view)
									.setScaleType(ImageView.ScaleType.CENTER_CROP);
							boolean firstDisplay = !displayedImages
									.contains(imageUri);
							if (firstDisplay) {
								FadeInBitmapDisplayer.animate((ImageView) view,
										500);
								displayedImages.add(imageUri);
							}
						}
					}

					@Override
					public void onLoadingFailed(String imageUri, View view,
							FailReason failReason) {
						Throwable cause = failReason.getCause();
//						MLog.e(TAG, cause.toString());
					}
				});
		// 圆形头像
		imageLoader.displayImage(articles.getDocImg(), uPhoto, options,
				new SimpleImageLoadingListener() {
					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {
						if (loadedImage != null) {
							((ImageView) view)
									.setScaleType(ImageView.ScaleType.CENTER_CROP);
							boolean firstDisplay = !displayedImages
									.contains(imageUri);
							if (firstDisplay) {
								FadeInBitmapDisplayer.animate((ImageView) view,
										500);
								displayedImages.add(imageUri);
							}
						}
					}

					@Override
					public void onLoadingFailed(String imageUri, View view,
							FailReason failReason) {
						Throwable cause = failReason.getCause();
//						MLog.e(TAG, cause.toString());
					}
				});
	}

	// ====ImageLoader start====
	public static final List<String> displayedImages = Collections
			.synchronizedList(new LinkedList<String>());
	// ImageLoaderOptions
	private DisplayImageOptions options;

	// ImageLoader
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	private String userid;

	private void initImageLoader() {
		options = new DisplayImageOptions.Builder()
				// .showImageForEmptyUri(R.drawable.ic_error) // resource or
				// drawable
				.showImageOnFail(R.drawable.imageloader_error)
				// resource or drawable
				.showStubImage(R.drawable.imageloader_default)
				.resetViewBeforeLoading(false)
				// default
				.cacheInMemory(true)
				.cacheOnDisc(true)
				// 精准
				.imageScaleType(ImageScaleType.EXACTLY)
				// ARGB_8888 每个像素要4字节~带透明度的颜色, 默认色样
				// RGB_565 每个像素要2字节~不带透明度的颜色
				.bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(new RoundedBitmapDisplayer(10)).build();
	}

	// ====ImageLoader end====

	public void onClickJkzh(View view) {
		switch (view.getId()) {
		case R.id.tv_jkgc_article_good:
			good();
			break;
		case R.id.tv_jkgc_article_share:
			share();
			break;
		case R.id.tv_jkgc_article_collect:
			collect();
			break;
		}
	}

	/**
	 * 1 .数据详情
	 */
	private void loadlist() {

		String action = getString(R.string.find_jkzh_article);

		// 请求参数
		HashMap<String, Object> inParams = new HashMap<String, Object>();
		inParams.put("art_id", artid);

		String request = "get";

		myProgress = new MyProgress(this, 10);
		myProgress.start();
		paser.setWhat(JkzhArticlePaser.ARTICLE);
		paser.sendMsg(action, inParams, request);
	}

	/**
	 * 2.赞
	 */
	private void good() {
		switch (praiseState) {
		case DEFAULT: // 当前页面状态是默认的；
			praiseState = HELPED;
			break;
		case HELPED:// 点击帮助的状态
			praiseState = DEFAULT;
			break;
		}
		saveState(praiseState);
		Stattistics(Sta_Help);
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Stattistics(Sta_Click);
	}

	/**
	 * 3. 分享
	 */
	private void share() {
//		share.setCompoundDrawables(null, shareDr, null, null);
//		this.sharePop();
		/**
		 * 分享
		 */
		if(article == null){
			Toast.makeText(this, "未获取数据,暂时不能分享", Toast.LENGTH_SHORT).show();
			return ;
		}
			ShareSDK.initSDK(this);
			OnekeyShare oks = new OnekeyShare();
			oks.setTitle("云健康");
			oks.setText(titleStr);
			oks.setUrl(article.getUrl());
			oks.setDialogMode();
			oks.setImageUrl(article.getArtImg());
			// 启动分享GUI
			oks.show(this,api);
			
			// 启动分享GUI
	}

	/**
	 * 4.收藏
	 */
	private void collect() {
//		collect.setCompoundDrawables(null, collectDr, null, null);

		// 请求地址
		String action = getString(R.string.find_collect);
		if(currentState == DEFAULT)
			 action = getString(R.string.find_collect);
		else
			action = getString(R.string.delete_collect);
		// 请求参数
		HashMap<String, Object> inParams = new HashMap<String, Object>();

		inParams.put("type", 5); // 所属类别

		inParams.put("userid", userid);
		inParams.put("art_id", artid);
		inParams.put("apptype", FindUtil.appid);
		String request = "get";
		myProgress = new MyProgress(this, 10);
		myProgress.start();
		paser.setWhat(JkzhArticlePaser.COLLECT);
		paser.sendMsg(action, inParams, request);
	}

	/**
	 * share事件，弹出popupWindow
	 */
//	private SharePopWindow window;

	private void sharePop() {
		// // 实例化 PopupWindow
		// window = new SharePopWindow(this, itemsOnClick);
		// // 显示窗口
		// window.showAtLocation(this.findViewById(R.id.ll_find_jkzh_article),
		// // 当前最外层的布局id
		//			Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
	}

	View.OnClickListener itemsOnClick = new View.OnClickListener() {
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.tv_wjk_plan_share_weixin:
				// Toast.makeText(mContext, "微信", Toast.LENGTH_SHORT).show();
//				window.shareWXPlatform(titleStr, contentStr);
				break;
			case R.id.tv_wjk_plan_share_xlwb:
//				window.shareSina(contentStr);
				break;
			case R.id.tv_wjk_plan_share_qq:
//				window.shareQQPlatform(titleStr, contentStr);
				break;
			case R.id.tv_wjk_plan_share_email:

				break;
			case R.id.tv_wjk_plan_share_pyq:
//				window.shareWXCirclePlatform(titleStr, contentStr);
				break;
			case R.id.tv_wjk_plan_share_txyb:
//				window.shareTencentPlatform(contentStr);
				break;
			}

		}
	};
	
	private void setDrawable(int state) {
//		switch (state) {
//		// 点击效果
//
//		case DEFAULT: // 当前页面状态是默认的；
//			goodD = this.getResources().getDrawable(
//					R.drawable.find_article_bar_1);
//			collectDr = this.getResources().getDrawable(
//					R.drawable.find_article_bar_3);
//			break;
//		case HELPED:// 点击帮助的状态
//			goodD = this.getResources().getDrawable(
//					R.drawable.find_article_bar_1_pressed);
//			collectDr = this.getResources().getDrawable(
//					R.drawable.find_article_bar_3);
//			break;
//		case COLLECTED:
//			goodD = this.getResources().getDrawable(
//					R.drawable.find_article_bar_1);
//			collectDr = this.getResources().getDrawable(
//					R.drawable.find_article_bar_3_pressed);
//			break;
//		case HELPED_AND_COLLECTED:
//			goodD = this.getResources().getDrawable(
//					R.drawable.find_article_bar_1_pressed);
//			collectDr = this.getResources().getDrawable(
//					R.drawable.find_article_bar_3_pressed);
//			break;
//		}
//		goodD.setBounds(0, 0, goodD.getMinimumWidth(), goodD.getMinimumHeight());
//		collectDr.setBounds(0, 0, collectDr.getMinimumWidth(),
//				collectDr.getMinimumHeight());
////		share.setCompoundDrawables(null, goodD, null, null);
//		collect.setCompoundDrawables(null, collectDr, null,
//				null);
		switch (state) {
		// 点击效果
		case DEFAULT: // 当前页面状态是默认的；
			tv_jkgc_article_collect.setImageResource(R.drawable.btn_detail_tab_3_normal);
			break;
		case COLLECTED:
			tv_jkgc_article_collect.setImageResource(R.drawable.btn_detail_tab_3_pressed);
			break;
		}
	}
	
	private void getState(){
		// 请求参数
		HashMap<String, Object> inParamsCollect = new HashMap<String, Object>();
		inParamsCollect.put("userid", userid);
		inParamsCollect.put("apptype", FindUtil.appid);
		String requestCollect = "get";
		paser.setWhat(JkzhArticlePaser.FIND);
		paser.sendMsg(getString(R.string.me_collect_list), inParamsCollect, requestCollect);
	}
	
	private final String STATE = "state";
	/**
	 * 保存当前页面状态
	 */
	private void saveState(int state) {

		editor = spState.edit();
		editor.putInt(artid + "", state);
		editor.commit();
		setHelpDrawable(state);
	}

	/**
	 * 获取当前页面状态；
	 * 
	 * @return
	 */
	private int getState(int id) {
		spState = getSharedPreferences(STATE, Context.MODE_PRIVATE);
		praiseState = spState.getInt(artid + "", DEFAULT);
		setHelpDrawable(praiseState);
		return praiseState;
	}
	
	/**
	 * 设置背景图片
	 * 
	 * @param state
	 */
	private void setHelpDrawable(int state) {
		switch (state) {
		// 点击效果

		case DEFAULT: // 当前页面状态是默认的；
//			goodD = this.getResources().getDrawable(
//					R.drawable.find_article_bar_1);
			tv_jkgc_article_good.setImageResource(R.drawable.btn_detail_tab_1_normal);
			break;
		case HELPED:// 点击帮助的状态
//			goodD = this.getResources().getDrawable(
//					R.drawable.find_article_bar_1_pressed);
			tv_jkgc_article_good.setImageResource(R.drawable.btn_detail_tab_1_pressed);
			break;
		}
//		goodD.setBounds(0, 0, goodD.getMinimumWidth(), goodD.getMinimumHeight());
//		good.setCompoundDrawables(null, goodD, null, null);
	}
	
	/**
	 * 友盟统计收藏 帮助
	 */
	public void Stattistics(int position){
		Map<String, String> params = new HashMap<String, String>();
		if(article == null || article.getUrl() == null)
			return;
		params.put("url",article.getUrl());
		if(position == Sta_Help){
			MobclickAgent.onEvent(this, "B00124", params);
		}else if(position ==Sta_Collect){
			MobclickAgent.onEvent(this, "B00123", params);
		}else {
			MobclickAgent.onEvent(this, "B00122", params);
		}
	}


}
